<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'

// 定义从父组件接收的场地信息属性
const props = defineProps<{
  place: {
    plId: number
    plName: string
    plPicture: string
    plAddress: string
    plCreateTime: string
    plMaxPeople: number
    isUsing: number
    plInfo: string
  }
}>()

// 定义 emits
const emit = defineEmits(['cancel', 'submit'])

// 创建表单数据模型
const form = ref({
  startDate: '',
  endDate: '',
  leaRemark: ''
})

// 创建响应式状态
const loading = ref(false)
const errorMessage = ref('')
const occupiedDates = ref<string[]>([])
const currentMonth = ref(new Date().getMonth())
const currentYear = ref(new Date().getFullYear())

// 获取图片完整路径
const getImageUrl = (picturePath: string) => {
  // 如果没有图片路径，返回空字符串
  if (!picturePath) return ''
  
  // 如果已经是完整URL，直接返回
  if (picturePath.startsWith('http')) {
    return picturePath
  }
  
  // 如果是绝对路径形式，拼接基础路径
  if (picturePath.startsWith('/')) {
    return `http://localhost:8080${picturePath}`
  }
  
  // 其他情况，也拼接基础路径
  return `http://localhost:8080/${picturePath}`
}

// 计算日历开始和结束日期
const calendarStartDate = computed(() => {
  const date = new Date(currentYear.value, currentMonth.value, 1)
  const dayOfWeek = date.getDay()
  const daysUntilMonday = dayOfWeek === 0 ? -6 : (1 - dayOfWeek)
  date.setDate(date.getDate() + daysUntilMonday)
  return date
})

const calendarEndDate = computed(() => {
  const date = new Date(currentYear.value, currentMonth.value + 1, 0)
  const dayOfWeek = date.getDay()
  const daysUntilSunday = dayOfWeek === 0 ? 0 : (7 - dayOfWeek)
  date.setDate(date.getDate() + daysUntilSunday)
  return date
})

// 获取当前月份的日期
const monthDates = computed(() => {
  const dates = []
  const currentDate = new Date(calendarStartDate.value)
  while (currentDate <= calendarEndDate.value) {
    dates.push(new Date(currentDate))
    currentDate.setDate(currentDate.getDate() + 1)
  }
  return dates
})

// 按周分组日期
const weeks = computed(() => {
  const weeks = []
  const dates = monthDates.value
  for (let i = 0; i < dates.length; i += 7) {
    weeks.push(dates.slice(i, i + 7))
  }
  return weeks
})

// 检查日期是否属于当前月份
const isCurrentMonth = (date: Date) => {
  return date.getMonth() === currentMonth.value && date.getFullYear() === currentYear.value
}

// 检查日期是否被占用
const isDateOccupied = (date: Date) => {
  const dateString = date.toISOString().split('T')[0]
  return occupiedDates.value.includes(dateString)
}

// 检查日期是否在选择的日期范围内
const isDateInRange = (date: Date) => {
  if (!form.value.startDate || !form.value.endDate) return false
  
  // 使用 YYYY-MM-DD 格式进行比较
  const dateStr = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
  return dateStr >= form.value.startDate && dateStr <= form.value.endDate
}

// 检查日期是否可选
const isDateSelectable = (date: Date) => {
  const today = new Date()
  today.setHours(0, 0, 0, 0) // 将时间设置为当天的开始
  return isCurrentMonth(date) && !isDateOccupied(date) && date >= today
}

// 检查日期是否是过去的日期
const isDateInPast = (date: Date) => {
  const today = new Date()
  today.setHours(0, 0, 0, 0) // 将时间设置为当天的开始
  return date < today
}

// 处理日期选择
const selectDate = (date: Date) => {
  // 使用 YYYY-MM-DD 格式而不依赖 toISOString()
  const dateStr = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
  
  if (!form.value.startDate) {
    // 如果还没有选择开始日期，则设置为开始日期
    form.value.startDate = dateStr
  } else if (!form.value.endDate) {
    // 如果已经有开始日期但没有结束日期
    if (dateStr < form.value.startDate) {
      // 如果选择的日期早于开始日期，则交换
      form.value.endDate = form.value.startDate
      form.value.startDate = dateStr
    } else {
      // 否则设置为结束日期
      form.value.endDate = dateStr
    }
  } else {
    // 如果两个日期都已选择，则重新开始选择
    form.value.startDate = dateStr
    form.value.endDate = ''
  }
}

// 切换到上一个月
const prevMonth = () => {
  if (currentMonth.value === 0) {
    currentMonth.value = 11
    currentYear.value--
  } else {
    currentMonth.value--
  }
}

// 切换到下一个月
const nextMonth = () => {
  if (currentMonth.value === 11) {
    currentMonth.value = 0
    currentYear.value++
  } else {
    currentMonth.value++
  }
}

// 获取月份名称
const getMonthName = (month: number) => {
  const months = ['一月', '二月', '三月', '四月', '五月', '六月', 
                 '七月', '八月', '九月', '十月', '十一月', '十二月']
  return months[month]
}

// 提交表单
const submitForm = async () => {
  console.log('开始提交表单')
  // 简单验证
  if (!form.value.startDate) {
    errorMessage.value = '开始日期不能为空'
    return
  }
  
  if (!form.value.endDate) {
    errorMessage.value = '结束日期不能为空'
    return
  }
  
  if (form.value.startDate > form.value.endDate) {
    errorMessage.value = '开始日期不能晚于结束日期'
    return
  }
  
  // 检查选择的日期范围内是否有被占用的日期
  const startDate = new Date(form.value.startDate)
  const endDate = new Date(form.value.endDate)
  const currentDate = new Date(startDate)
  
  while (currentDate <= endDate) {
    if (isDateOccupied(currentDate)) {
      errorMessage.value = '选择的日期范围内包含已被占用的日期，请重新选择'
      return
    }
    currentDate.setDate(currentDate.getDate() + 1)
  }
  
  // 检查租用用意是否填写
  if (!form.value.leaRemark.trim()) {
    errorMessage.value = '请填写租用用意'
    return
  }
  
  // 发送申请数据到后端
  try {
    loading.value = true
    const token = localStorage.getItem('token')
    if (!token) {
      throw new Error('未找到身份凭证，请重新登录')
    }
    
    console.log('准备发送请求，token:', token)
    const requestData = {
      plId: props.place.plId,
      startDate: `${form.value.startDate}T09:00:00`,
      endDate: `${form.value.endDate}T17:00:00`,
      leaRemark: form.value.leaRemark
    }
    console.log('请求数据:', requestData)
    
    const response = await fetch('http://localhost:8080/place_app/apply', {
      method: 'POST',
      headers: {
        'token': token,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(requestData)
    })
    
    console.log('收到响应:', response)
    const result = await response.json()
    console.log('响应数据:', result)
    
    if (result.code === 200) {
      // 申请成功
      console.log('申请提交成功')
      emit('submit', {
        placeId: props.place.plId,
        ...form.value
      })
    } else {
      errorMessage.value = result.msg || '申请提交失败'
    }
  } catch (err: any) {
    console.error('申请提交失败:', err)
    errorMessage.value = err.message || '申请提交失败，请稍后重试'
  } finally {
    loading.value = false
  }
}

// 添加一个测试函数，用于调试
const testSubmit = () => {
  console.log('测试提交功能')
  console.log('表单数据:', form.value)
  submitForm()
}

// 取消操作
const goBack = () => {
  emit('cancel')
}

// 获取已占用的日期
const fetchOccupiedDates = async () => {
  try {
    const token = localStorage.getItem('token')
    if (!token) {
      throw new Error('未找到身份凭证，请重新登录')
    }
    
    const response = await fetch(`http://localhost:8080/placeRecord/listByPlace?placeId=${props.place.plId}`, {
      method: 'GET',
      headers: {
        'token': token,
        'Content-Type': 'application/json'
      }
    })
    
    const result = await response.json()
    
    if (result.msg === '操作成功' && Array.isArray(result.data)) {
      // 提取日期部分并存储
      occupiedDates.value = result.data.map((record: any) => {
        // 使用 YYYY-MM-DD 格式而不依赖 toISOString()
        const date = new Date(record.appTime)
        return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
      })
    }
  } catch (err) {
    console.error('获取场地租借情况失败:', err)
  }
}

// 组件挂载时获取已占用日期
onMounted(() => {
  fetchOccupiedDates()
})
</script>

<template>
  <div class="new-place-app-container">
    <div class="place-info-section">
      <div class="place-detail">
        <div class="place-image-info">
          <div class="place-image">
            <img 
              v-if="place.plPicture" 
              :src="getImageUrl(place.plPicture)" 
              :alt="place.plName" 
              @error="($event) => { ($event.target as HTMLImageElement).src = ''; }"
            />
            <div v-else class="no-image">无图片</div>
          </div>
          <div class="place-info">
            <div class="info-row">
              <span class="label">场地名称:</span>
              <span>{{ place.plName }}</span>
            </div>
            <div class="info-row">
              <span class="label">地址:</span>
              <span>{{ place.plAddress }}</span>
            </div>
            <div class="info-row">
              <span class="label">最大容纳人数:</span>
              <span>{{ place.plMaxPeople }}人</span>
            </div>
            <div class="info-row">
              <span class="label">描述:</span>
              <span>{{ place.plInfo }}</span>
            </div>
        <div class="date-range-group">
            <div class="form-group-inline">
              <label for="startDate">开始日期:</label>
              <input
                id="startDate"
                v-model="form.startDate"
                type="date"
                class="form-input"
              />
            </div>
            
            <div class="form-group-inline">
              <label for="endDate">结束日期:</label>
              <input
                id="endDate"
                v-model="form.endDate"
                type="date"
                class="form-input"
              />
            </div>
      </div>

      <div class="form-group">
        <label for="leaRemark">用途:</label>
        <textarea
          id="leaRemark"
          v-model="form.leaRemark"
          class="form-textarea"
          rows="2"
          placeholder="请输入租用场地的具体用意"
        ></textarea>
      </div>
      
      <div class="error-message" v-if="errorMessage">
        {{ errorMessage }}
      </div>
          </div>
        </div>
        
        <div class="calendar-section">
          <div class="calendar-header">
            <button @click="prevMonth" class="nav-button">&lt;</button>
            <span class="month-year">{{ currentYear }}年{{ getMonthName(currentMonth) }}</span>
            <button @click="nextMonth" class="nav-button">&gt;</button>
          </div>
          <div class="calendar-grid">
            <div class="calendar-weekdays">
              <div class="weekday">日</div>
              <div class="weekday">一</div>
              <div class="weekday">二</div>
              <div class="weekday">三</div>
              <div class="weekday">四</div>
              <div class="weekday">五</div>
              <div class="weekday">六</div>
            </div>
            <div 
              v-for="(week, weekIndex) in weeks" 
              :key="weekIndex" 
              class="calendar-week"
            >
              <div
                v-for="date in week"
                :key="date.toISOString()"
                :class="[
                  'calendar-day',
                  {
                    'current-month': isCurrentMonth(date),
                    'other-month': !isCurrentMonth(date),
                    'selected': isDateInRange(date),
                    'occupied': isDateOccupied(date),
                    'selectable': isDateSelectable(date),
                    'start-date': form.startDate === `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`,
                    'end-date': form.endDate === `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`,
                    'disabled': isDateInPast(date)
                  }
                ]"
                @click="isDateSelectable(date) ? selectDate(date) : null"
              >
                {{ date.getDate() }}
              </div>
            </div>
          </div>

          <div class="calendar-legend">
            <div class="legend-item">
              <div class="legend-color available"></div>
              <span>可选日期</span>
            </div>
            <div class="legend-item">
              <div class="legend-color occupied"></div>
              <span>已占用</span>
            </div>
            <div class="legend-item">
              <div class="legend-color selected"></div>
              <span>已选择</span>
            </div>
            <div class="legend-item">
              <div class="legend-color other-month"></div>
              <span>非当前月</span>
            </div>
            <div class="legend-item">
              <div class="legend-color disabled"></div>
              <span>已过期</span>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <div class="form-actions">
      <button 
        @click="goBack"
        class="cancel-button"
        :disabled="loading"
      >
        取消
      </button>

      <button 
        @click="submitForm"
        class="submit-button"
        :disabled="loading"
      >
        {{ loading ? '提交中...' : '提交申请' }}
      </button>
    </div>
  </div>
</template>

<style scoped>
.new-place-app-container {
  width: 100%;
  padding: 20px;
}

.new-place-app-container h2 {
  color: #333;
  font-size: 2rem;
  margin-bottom: 20px;
  text-align: center;
}

.place-info-section {
  background: white;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.place-info-section h3 {
  margin-top: 0;
  color: #333;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
}

.place-detail {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.place-image-info {
  display: flex;
  gap: 20px;
}

.place-image {
  flex: 1;
}

.place-image img {
  width: 200px;
  height: 200px;
  object-fit: cover;
  border-radius: 8px;
}

.no-image {
  width: 200px;
  height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f5f5;
  border: 1px dashed #ddd;
  border-radius: 8px;
  color: #999;
}

.place-info {
  flex: 2;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.calendar-section {
  margin-top: 20px;
}

.calendar-section h4 {
  margin-top: 0;
  color: #333;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
}

.calendar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.nav-button {
  background: #3498db;
  color: white;
  border: none;
  border-radius: 4px;
  width: 30px;
  height: 30px;
  cursor: pointer;
  font-size: 16px;
}

.month-year {
  font-weight: bold;
  font-size: 18px;
}

.calendar-grid {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.calendar-weekdays {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  text-align: center;
  font-weight: bold;
  color: #555;
}

.calendar-week {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 5px;
}

.calendar-day {
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.2s;
  border: 1px solid #ddd;
  position: relative;
}

.calendar-day.current-month {
  background-color: #fff;
}

.calendar-day.other-month {
  background-color: #f5f5f5;
  color: #bbb;
  cursor: default;
}

.calendar-day.selectable:hover {
  background-color: #f0f0f0;
}

.calendar-day.selected {
  background-color: #3498db;
  color: white;
  border-color: #3498db;
}

.calendar-day.start-date::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  border: 2px solid #27ae60;
  border-radius: 4px;
  pointer-events: none;
}

.calendar-day.end-date::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  border: 2px solid #e74c3c;
  border-radius: 4px;
  pointer-events: none;
}

.calendar-day.occupied {
  background-color: #e0e0e0;
  color: #999;
  cursor: not-allowed;
  border-color: #ccc;
}

.calendar-day.disabled {
  background-color: #f5f5f5;
  color: #bbb;
  cursor: not-allowed;
  border-color: #ddd;
}

.calendar-legend {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin-top: 15px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 5px;
}

.legend-color {
  width: 20px;
  height: 20px;
  border-radius: 4px;
}

.legend-color.available {
  border: 1px solid #ddd;
}

.legend-color.occupied {
  background-color: #e0e0e0;
}

.legend-color.selected {
  background-color: #3498db;
}

.legend-color.other-month {
  background-color: #f5f5f5;
}

.legend-color.disabled {
  background-color: #f5f5f5;
}

.form-container {
  background: white;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.form-container h3 {
  margin-top: 0;
  color: #333;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: bold;
  color: #555;
}

.date-range-group {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin-bottom: 20px;
}

.form-group-inline {
  display: inline-flex;
  align-items: center;
}

.form-group-inline label {
  margin-right: 8px;
  font-weight: bold;
  color: #555;
  white-space: nowrap;
}

.form-group-inline .form-input {
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 5px;
  font-size: 16px;
  box-sizing: border-box;
}

.form-input:focus,
.form-textarea:focus {
  outline: none;
  border-color: #3498db;
  box-shadow: 0 0 5px rgba(52, 152, 219, 0.3);
}

.form-textarea {
  resize: vertical;
  font-family: inherit;
}

.info-row {
  display: flex;
  flex-wrap: wrap;
}

.label {
  font-weight: bold;
  min-width: 120px;
  margin-right: 10px;
  color: #555;
}

.error-message {
  color: #e74c3c;
  margin-bottom: 20px;
  padding: 10px;
  background-color: #fdf2f2;
  border: 1px solid #f5c6cb;
  border-radius: 5px;
}

.form-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 30px;
}

.cancel-button,
.submit-button {
  padding: 12px 30px;
  border: none;
  border-radius: 5px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.cancel-button {
  background-color: #95a5a6;
  color: white;
}

.cancel-button:hover:not(:disabled) {
  background-color: #7f8c8d;
}

.cancel-button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.submit-button {
  background-color: #27ae60;
  color: white;
}

.submit-button:hover:not(:disabled) {
  background-color: #219653;
}

.submit-button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

@media (max-width: 768px) {
  .place-image-info {
    flex-direction: column;
  }
}
</style>